function BCAgetArmor () {
    // Install checkboxes in front of other ships pilots names
    if (POisPartialRefresh()) {
        var ship = window.shipTab;
    } else {
        var ship = document.getElementById ("yourship_content");
    }
    var fnts = ship.getElementsByTagName ("font");
    for (var i=0; i<fnts.length; i++) {
        if (fnts[i].textContent.indexOf ("Armor:") != -1) {
            var td = fnts[i].parentNode.nextSibling;
            return Number (td.getElementsByTagName ("font")[0].textContent);
        }
    }
    return -1;
}

function BCAgetArmorMax () {
    // Install checkboxes in front of other ships pilots names
    if (POisPartialRefresh()) {
        var ship = window.shipTab;
    } else {
        var ship = document.getElementById ("yourship_content");
    }
    var fnts = ship.getElementsByTagName ("font");
    for (var i=0; i<fnts.length; i++) {
        if (fnts[i].textContent.indexOf ("Armor:") != -1) {
            var td = fnts[i].parentNode.nextSibling;
            return Number (td.getElementsByTagName ("font")[1].textContent.substr(2));
        }
    }
    return -1;
}

function BCAgetResource (resName) {
    // Install checkboxes in front of other ships pilots names
    if (POisPartialRefresh()) {
        var ship = window.cargoTab;
    } else {
        var ship = document.getElementById ("cargo_content");
    }
    var imgs = ship.getElementsByTagName ("img");
    for (var i=0; i<imgs.length; i++) {
        if (imgs[i].getAttribute ("title") == resName) {
            return Number (imgs[i].nextSibling.textContent.substr(1))
        }
    }
    return -1;
}

function BCAgetBotsToTake () {
    var avail = BCAgetResource ("Robots");
    if (avail<1) return 0;
    
    return POgetBotsToRepair (Number(localStorage.getItem("po_bca_armor_strength")), BCAgetArmor (), BCAgetArmorMax ());
}

function BCAgetDrugsToTake () {
    var avail = BCAgetResource ("Drugs");
    if (avail<1) return 0;
    var defAmount = localStorage.getItem ('po_bca_default_drugs');
    return defAmount>avail?avail:defAmount;
}

function BCAinstallRetreatPath () {
    // Add the control panel for sighting reporting.
    var status = document.getElementById ("commands");
    if (!status) return;

    // Check if the stuff is already installed. If so, delete it first
    var tr = document.getElementById ("po_bca_retreat_path");
    if (tr) tr.parentNode.removeChild (tr);

    // Check if the retreat path is set
    var value = "";
    var rp = localStorage.getItem ("po_bca_retreat_path");
    var botsToTake = BCAgetBotsToTake ();
    var drugsToTake = BCAgetDrugsToTake ();
    if (!rp && !botsToTake && !drugsToTake) return;

    // Create a new row in the Status table and insert it
    tr = document.createElement ("tr");
    tr.id = "po_bca_retreat_path";
    status.firstChild.insertBefore (tr, status.firstChild.lastChild);
    td = status.firstChild.childNodes[1].firstChild.cloneNode(false);
    tr.appendChild (td);
    
    if (rp) value += "<br>"+rp;
    if (botsToTake) value += "<br><span style='margin: 0pt 18px;'><a id='bca_bots_to_take' style='color:lime;' href='javascript:BCAtakeBots("+botsToTake+");void(0);'>4 - use "+botsToTake+" robots</a></span>";
    if (drugsToTake) value += "<br><span style='margin: 0pt 18px;'><a id='bca_drugs_to_take' style='color:lime;' href='javascript:BCAtakeDrugs("+drugsToTake+");void(0);'>5 - use "+drugsToTake+" drugs</a></span>";
    
    td.innerHTML = value;
    if (td.firstChild.tagName.toLowerCase() == "br")
        td.removeChild (td.firstChild);
}

function BCAinnerSB () {
    var links = document.links;
    for (var i=0; i<links.length; i++) {
        if (links[i].textContent == "Exit inner starbase") return true;
    }
    return false;
}

// Make sure it will work with PartialRefresh
function BCAhijackShip () {
    var local_method = window.updateShip;
    if (local_method != undefined) {
        window.updateShip = function(cmd) {
            local_method(cmd);
            BCAinstallRetreatPath ();
        }
    }
}

function BCAhijackCargo () {
    var local_method = window.updateCargo;
    if (local_method != undefined) {
        window.updateCargo = function(cmd) {
            local_method(cmd);
            BCAinstallRetreatPath ();
        }
    }
}

function BCAtrackLastTile () {
    var loc = window.userloc;
    localStorage.setItem ("po_bca_last_tile", localStorage.getItem ("po_bca_current_tile"));
    localStorage.setItem ("po_bca_current_tile", loc);
}

// Make sure it will work with PartialRefresh
function BCAhijackStatus () {
    var local_method = window.updateStatus;
    if (local_method != undefined) {
        window.updateStatus = function(cmd) {
            local_method(cmd);
            BCAtrackLastTile ();
        }
    }
}

window.onload = setTimeout(function () {
    BCAinstallRetreatPath ();
    BCAtrackLastTile ();
    BCAhijackShip ();
    BCAhijackCargo ();
    BCAhijackStatus ();
}, 1)

// //////////////////////////////////////////////////////////
// Hotkeys
// //////////////////////////////////////////////////////////
window.addEventListener("keypress",BCAkeyboardAction,true);

function BCAkeyboardAction (e) {
    if(window.name == '' || e.ctrlKey) return;
    if (e.target.nodeName.toUpperCase() == 'INPUT' || e.target.nodeName.toUpperCase() == 'TEXTAREA') return;
    var keynum = e.which;
    var key = String.fromCharCode(keynum).toLowerCase();
    
    if (key == "3") BCAfightFirst ();
    else if (key == "1") BCAretreat ();
    else if (key == "2") BCArefreshScreen ();
    else if (key == "4") BCAtakeBots (-1);
    else if (key == "5") BCAtakeDrugs (-1);
    else if (key == "0") BCAsetRetreat ();
    else if (key == "e") BCAgetShipStats ();
    else if (key == "k") BCAcloak ();
    else if (key == "l") BCAambush ();
    else if (key == "r") BCArepair ();
}

function BCArepair () {
    window.location = "ship_equipment.php";
}

function BCAambush () {
    window.location = "ambush.php";
}

function BCAcloak () {
    if (POisPartialRefresh()) {
        window.cloak (0);
    } else {
        document.cloaking.submit();
    }
}

function BCAsetRetreat () {
    if (BCAinnerSB()) return;
    var div = document.createElement ("div");
    var loc = POgetLocation ();
    var userloc = window.userloc;
    var value = "<span style='color:lime;font-weight:bold;margin: 0pt 18px;'><a style='color:red;' href='javascript:BCAresetRP();void(0);'>X</a> RP: <a style='color:lime;' userloc='"+userloc+"' href='javascript:BCAretreat();void(0);'>"+loc+"</a></span>";
    localStorage.setItem ("po_bca_retreat_path", value);
    BCAinstallRetreatPath ();
}

function BCAfightFirst () {
    if (POisPartialRefresh()) {
        var ops = window.shipsTab;
    } else {
        var ops = document.getElementById ("otherships_content");
    }
    var otherShips = ops.childNodes;
    if (otherShips.length == 0) {
        window.location = "main.php";
        return;
    }
    var pilot = null;
    for (var i=0; i<otherShips.length; i++) {
        var os = otherShips[i];
        var ff = Number (os.getAttribute ("po_ffm_ff"));
        if (ff >= 0) continue;
        if (os.getAttribute("bca_attackable") == "false") continue;
        pilot = os;
        break;
    }
    if (pilot) {
        var id = pilot.getAttribute ("po_ffm_id");
        window.location = "ship2ship_combat.php?playerid="+id;
    } else BCArefreshScreen();
}

function BCAresetRP() {
    localStorage.removeItem ("po_bca_retreat_path");
    BCAinstallRetreatPath ();
}

function BCAretreat () {
    if (BCAinnerSB ()) {
        window.location = "main.php?exitsb=1";
        return;
    }
    
    // Check if the retreat path is set
    value = localStorage.getItem ("po_bca_retreat_path");
    if (!value || value.length == 0) {
        var loc = localStorage.getItem ("po_bca_last_tile");
    } else {
        var div = document.createElement ("div");
        div.innerHTML = value;
        var loc = div.firstChild.lastChild.getAttribute ("userloc");
    }
    // Jump to the location
    if (loc) {
        if (window.navAjax) {
            window.navAjax (loc);
        } else {
            window.nav (loc);
        }
    }
}

function BCArefreshScreen () {
    window.location = "main.php";
}

function BCAtakeBots (amount) {
    if (amount == -1) {
        var elem = document.getElementById ("bca_bots_to_take");
        if (elem) elem.click ();
        return;
    }
    POuseResource (8, amount, BCArefreshScreen);
}

function BCAtakeDrugs (amount) {
    if (amount == -1) {
        var elem = document.getElementById ("bca_drugs_to_take");
        if (elem) elem.click ();
        return;
    }
    POuseResource (51, amount, BCArefreshScreen);
}

function BCAgetShipStats () {
    if (POisPartialRefresh()) {
        var ops = window.shipsTab;
    } else {
        var ops = document.getElementById ("otherships_content");
    }
    var otherShips = ops.childNodes;

    for (var i=0; i<otherShips.length; i++) {
        var processed = otherShips[i].getAttribute ("bca_processed");
        if (processed == "true") continue;
        var id = otherShips[i].getAttribute ("po_ffm_id");
        POgetOtherShipInfo (id, BCAshowShipStats);
        break;
    }
}

function BCAshowShipStats (status, pilotID, ship, hull, armor, shield) {
    if (POisPartialRefresh()) {
        var ops = window.shipsTab;
    } else {
        var ops = document.getElementById ("otherships_content");
    }
    var otherShips = ops.childNodes;

    var pilot = null;
    for (var i=0; i<otherShips.length; i++) {
        var id = otherShips[i].getAttribute ("po_ffm_id");
        if (id != pilotID) continue;
        pilot = otherShips[i];
        break;
    }

    if (!pilot) return;
    pilot.setAttribute ("bca_processed", "true");
    var str;
    if (!status) {
        str = "<span style='color:lime;font-size:10px;font-weight:bold'>Can't be attacked</span>";
        pilot.setAttribute ("bca_attackable", "false");
    } else {
        str = "<span style='color:red;font-size:10px;font-weight:bold'>H:"+hull+"&nbsp;A:"+armor+"&nbsp;S:"+shield+"</span>";
        pilot.setAttribute ("bca_attackable", "true");
    }
    pilot.firstChild.firstChild.lastChild.appendChild (document.createElement("br"));
    var div = document.createElement ("div");
    div.innerHTML = str;
    pilot.firstChild.firstChild.lastChild.appendChild (div.firstChild);
}

// //////////////////////////////////////////////////////////
// End: Hotkeys
// //////////////////////////////////////////////////////////